package com.fubowen.lepton.extension

import android.webkit.WebView

const val DOCUMENT_ELEMENT = "(function() { return document.documentElement.outerHTML; })();"
const val CANONICAL = "document.querySelector('link[rel=canonical]').getAttribute('href')"
fun WebView.documentText(callback: (String) -> Unit) {
    this.evaluateJavascript(DOCUMENT_ELEMENT) { text ->
        val regex = Regex("\\\\u[0-9A-Fa-f]{4}")
        val html = text
            .substring(1, text.length - 1)
            .replace(regex) { it.value.replace("\\u", "").toInt(16).toChar().toString() }
            .replace("\\", "")
        callback(html)
    }
}

fun WebView.getCanonical(callback: (String) -> Unit) {
    this.evaluateJavascript(CANONICAL) {
        val canonical = it?.trim('"') ?: ""
        callback(canonical)
    }
}

fun WebView.isErrorPage() {
//    this.title != null && this.title.contains("Error") || url.contains("error")
}